package com.bjdd.jdy.ui.userCenter;

import com.bjdd.jdy.util.JumpUtil;
import com.bjdd.jdy.util.L;
import com.bjdd.jdy.util.SpUtil;
import com.bjdd.jdy.util.T;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Administrator on 2017/4/20.
 */

public class UserCenterPresenter extends UserCenterContract.Presenter {
    @Override
    public void onStart() {
        if (SpUtil.getUser() == null || SpUtil.getUser().equals("") || SpUtil.getUser().getCarrierId() == null) {
            JumpUtil.toLogin(context);
            return;
        }
        getInfo();
    }

    @Override
    void getInfo() {
        showLoadingDialog(false);
        String token = SpUtil.getToken();
        String carrierId = SpUtil.getUser().getCarrierId();
        rxManager.add(model.getInfo(token,carrierId)
        .subscribe(result -> {
            hideLoadingDialog();
            if (!result.isError()){
                view.infoSuccess(result.getData());
            }else {
                T.show(result.getMsg());
            }
        },e -> {
            hideLoadingDialog();
            T.show("获取数据失败");
        }));
    }

    @Override
    void headPhoto(RequestBody img) {
        //showLoadingDialog(false);
        String token = SpUtil.getToken();
        String carrierId = SpUtil.getUser().getCarrierId();
        rxManager.add(model.headPhoto(token,carrierId,img)
        .subscribe(result -> {
            hideLoadingDialog();
            if (!result.isError()){
                SpUtil.setUser(result.getData());
                view.headPhotoSuccess();
            }else {
                T.show(result.getMsg());
            }
        },e -> {
            hideLoadingDialog();
            T.show("上传头像失败");
            L.d("错误信息："+e.getMessage());
        }));
    }

    @Override
    void CompressImg(File file) {
        showLoadingDialog(false);
        Luban.get(context)
                .load(file)
                .putGear(Luban.THIRD_GEAR)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
                        headPhoto(requestBody);
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoadingDialog();
                        T.show(e.getMessage());
                    }
                }).launch();
    }

}
